package com.mytx.search.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mytx.common.annotation.SerializedField;
import com.mytx.common.constant.Constant;
import com.mytx.common.pojo.CommonResult;
import com.mytx.common.pojo.Notify;
import com.mytx.common.utils.EntityUtils;
import com.mytx.mapper.LiveRoomMapper;
import com.mytx.mapper.TopicMapper;
import com.mytx.mapper.UserMapper;
import com.mytx.pojo.LiveRoom;
import com.mytx.pojo.Message;
import com.mytx.pojo.Topic;
import com.mytx.pojo.User;
import com.mytx.search.config.EsSearchClient;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.OpenImUser;
import com.taobao.api.domain.TribeInfo;
import com.taobao.api.request.OpenimCustmsgPushRequest;
import com.taobao.api.request.OpenimTribeCreateRequest;
import com.taobao.api.response.OpenimCustmsgPushResponse;
import com.taobao.api.response.OpenimTribeCreateResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 主题服务的相关操作
 */
@SuppressWarnings("ALL")
@RestController
public class TopicController {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TopicController.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private EsSearchClient searchClient;

    @Autowired
    private SearchController searchController;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TaobaoClient taobaoClient;

    @Autowired
    private LiveRoomMapper liveRoomMapper;

    @Value("${ali.appKey}")
    private String appKey;

    @Value("${phone_number_match}")
    String phoneNumberMatch;

    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 退出主题管理
     * @param topic 主题id
     * @return
     */
    @PostMapping("/exitMangerTopic")
    public CommonResult exitMangerTopic(@RequestBody String topicId){
        //1.获取当前的登录的用户id
        String uId = request.getHeader("uId");
        logger.info("exitMangerTopic:管理员退出主题管理:uId:{}",uId);
        Topic tableTopic = topicMapper.selectByPrimaryKey(topicId);
        //2.登录用户是否有权限
        if (!StringUtils.equals(tableTopic.getManagerId(), uId)) {//判断请求者是否是管理员
            logger.error("转发捐款无权限：uId:{},manger:{}" + uId, tableTopic.getManager());
            return CommonResult.build(Constant.DONATION_FORWARD_NO_AUTHORIZATION, "你不是管理员，没有权限");
        }
        //判断主题的类型
        Integer topicType = tableTopic.getType();
        if (!(Constant.TOPIC_TYPE_SCHOOL==topicType||Constant.TOPIC_TYPE_AREA==topicType||Constant.TOPIC_TYPE_INDUSTRY==topicType)){
            logger.error("exitMangerTopic:用户退出主题管理错误:只有学校,行业,地区才能退出主题管理:uId:{},topicId:{}",uId,topicId);
            return CommonResult.build(Constant.PARAMETER_INVALID,"主题类型不正确");
        }
        //3.分别将es和数据库的主题数据中的管理员信息清除
        topicMapper.updateManagerNullByTopicId(topicId);
        logger.info("exitManagerTopic:删除数据库中的主题的管理员信息成功:topicId:{}",topicId);
        Map<String , Object> info = new HashMap<>();
        info.put("topicId", topicId);
        List<String> fileldNameList = new ArrayList<>();
        fileldNameList.add("manager");
        fileldNameList.add("author");
        info.put("fieldName",fileldNameList);
        CommonResult commonResult =  searchController.deleteField(info);
        if (commonResult.getStatus()==CommonResult.STATUS_FAIL){
            logger.error("exitManagerTopic:删除ES中主题的管理员字段失败:topicId:{}",topicId);
            return commonResult;
        }
        logger.info("exitManagerTopic:删除ES中主题的管理员字段成功:topicId:{}",topicId);
        return CommonResult.ok();
    }

    /**
     * 让度管理
     * @param body
     * @return
     */
    @PostMapping("/surrenderMangerTopic")
    public CommonResult surrenderMangerTopic(@RequestBody Map<String,Object> body) throws ApiException {
        //1.获取当前操作的用户id
        String uId = request.getHeader("uId");
        logger.info("surrenderMangerTopic:管理员让渡管理:uId:{}",uId);
        String topicId = (String) body.get("topicId");
        String newMangerId = (String)body.get("newMangerId");
        //2.登录用户是否有权限
        Topic tableTopic = topicMapper.selectByPrimaryKey(topicId);
        if (!StringUtils.equals(tableTopic.getManagerId(), uId)) {//判断请求者是否是管理员
            logger.error("转发捐款无权限：uId:{},manger:{}" + uId, tableTopic.getManager());
            return CommonResult.build(Constant.DONATION_FORWARD_NO_AUTHORIZATION, "你不是管理员，没有权限");
        }
        //3.判断主题的类型是否正确
        //判断主题的类型
        Integer topicType = tableTopic.getType();
        if (!(Constant.TOPIC_TYPE_SCHOOL==topicType||Constant.TOPIC_TYPE_AREA==topicType||Constant.TOPIC_TYPE_INDUSTRY==topicType)){
            logger.error("surrenderMangerTopic:用户让度主题管理错误:只有学校,行业,地区才能让度主题管理:uId:{},topicId:{},newManger",uId,topicId,newMangerId);
            return CommonResult.build(Constant.PARAMETER_INVALID,"主题类型不正确");
        }
        //3.分别将es和数据库中的管理员id修改为新的管理员id
        Topic newTopic = new Topic();
        newTopic.setId(topicId);
        newTopic.setManagerId(newMangerId);
        Date updateDate = new Date();
        newTopic.setUpdated(updateDate);
        topicMapper.updateByPrimaryKeySelective(newTopic);
        logger.info("surrenderMangerTopic:修改数据库中的主题的管理员信息成功:topicId:{},newManger",topicId,newMangerId);
        User tableAuthor = userMapper.selectByPrimaryKey(newMangerId);
        User author = new User();
        author.setuId(newMangerId);
        author.setFollow(false);
        author.setUsername(tableAuthor.getUsername());
        author.setAvatar(tableAuthor.getAvatar());
        newTopic.setManager(author);
        CommonResult commonResult = searchController.update(newTopic);
        if (commonResult.getStatus()!=CommonResult.STATUS_SUCCESS){
            logger.error("surrenderMangerTopic:修改ES中主题的管理员信息失败:topicId:{},newManger",topicId,newMangerId);
            return commonResult;
        }
        logger.info("surrenderMangerTopic:修改ES中主题的管理员信息成功:topicId:{},newManger",topicId,newMangerId);
        //调用阿里云旺api新建一个群,将群主设置为新的管理者
        OpenImUser user = new OpenImUser();
        user.setUid(newMangerId);
        user.setAppKey(appKey);
        user.setTaobaoAccount(false);
        OpenimTribeCreateRequest createRequest = new OpenimTribeCreateRequest();
        createRequest.setUser(user);
        createRequest.setNotice(tableTopic.getTitle());
        createRequest.setTribeName(tableTopic.getTitle());
        createRequest.setTribeType(0L);
        OpenimTribeCreateResponse response = taobaoClient.execute(createRequest);
        if (!response.isSuccess()) {
            logger.error("createTopicAndLiveRoom:创建群失败" + response.getErrorCode() + response.getMsg());
            return CommonResult.build(CommonResult.STATUS_FAIL, "创建群失败");
        }
        TribeInfo tribeInfo = response.getTribeInfo();
        System.out.println();
        //以阿里云旺群id 为主题id
        String newChatId = String.valueOf(tribeInfo.getTribeId());
        //返回的群id设置为聊天室的chatId
        LiveRoom liveRoom = new LiveRoom();
        liveRoom.setId(topicId);
        liveRoom.setChatId(newChatId);
        liveRoom.setManagerId(newMangerId);
        liveRoom.setUpdated(new Date());
        liveRoomMapper.updateByPrimaryKeySelective(liveRoom);
        Map<String, Object> liveRoomObjectMap = EntityUtils.objectToMap_v1(liveRoom);
        //修改缓存中的聊天室的信息
        Object chatIdObj = redisTemplate.opsForHash().get(Constant.LIVE_ROOM + topicId, "chatId");
        String oldChatId= null;
        if(chatIdObj!=null&&chatIdObj instanceof  String) {
            oldChatId = (String) chatIdObj;
            JSONObject chatJSON = new JSONObject();
            body.put("oldChatId", oldChatId);
            body.put("newChatId", newChatId);
            body.put("oldManger",uId);
            redisTemplate.convertAndSend(Constant.NOTIFY_CHATID_CHANGE_INFO,chatJSON);
        }
        redisTemplate.opsForHash().putAll(Constant.LIVE_ROOM+topicId,liveRoomObjectMap);
        //4.推送一条让度成功的消息给新的管理员
        Message notify = new Message();
        JSONObject notifyData = new JSONObject();
        notify.setType(Constant.PUSH_MESSAGE_NEW_MANGER);
        Topic notifyTopic = new Topic();
        notifyTopic.setId(topicId);
        notifyTopic.setTitle(tableTopic.getTitle());
        notifyTopic.setPictures(tableTopic.getPictures());
        notifyTopic.setUpdated(updateDate);
        notifyData.put("notifyTopic",notifyTopic);
        notifyData.put("oldManger",uId);
        notify.setExtraData(notifyData);
        List<String> userIdList = new ArrayList<>();
        userIdList.add(newMangerId);
        JSONObject info = new JSONObject();
        info.put("userIdList",userIdList);
        info.put("message",notify);
        redisTemplate.convertAndSend(Constant.NOTIFY_PUSH_MESSAGE,info);
        logger.info("surrenderMangerTopic:向新的管理员推送消息成功:newManger:{},data:{}",newMangerId,topicId);
        return CommonResult.ok();
    }




}
